package com.css.fxfzypg.modules.rating.task.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.modules.group.entity.GroupEntity;
import com.css.fxfzypg.modules.group.entity.UserEntity;
import com.css.fxfzypg.modules.group.service.GroupService;
import com.css.fxfzypg.modules.group.vo.GroupMemberVo;
import com.css.fxfzypg.modules.message.repository.entity.MessageEntity;
import com.css.fxfzypg.modules.message.service.MessageService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.rating.expertRating.constants.KpExpertRatingStatus;
import com.css.fxfzypg.modules.rating.expertRating.dao.KpRatingTaskExpertDao;
import com.css.fxfzypg.modules.rating.expertRating.dao.KpRatingTaskExpertScoreProgressDao;
import com.css.fxfzypg.modules.rating.expertRating.model.entity.KpRatingTaskExpert;
import com.css.fxfzypg.modules.rating.expertRating.model.entity.KpRatingTaskExpertScoreProgress;
import com.css.fxfzypg.modules.rating.expertRating.service.KpExpertRatingService;
import com.css.fxfzypg.modules.rating.library.dao.KpExamScoringDbIndex2Repository;
import com.css.fxfzypg.modules.rating.library.dao.KpExamScoringDbIndex3Repository;
import com.css.fxfzypg.modules.rating.library.model.entity.KpExamScoringDb;
import com.css.fxfzypg.modules.rating.library.model.entity.KpExamScoringDbIndex2;
import com.css.fxfzypg.modules.rating.library.model.entity.KpIndex3Data;
import com.css.fxfzypg.modules.rating.library.model.vo.*;
import com.css.fxfzypg.modules.rating.library.service.KpExamScoringDbService;
import com.css.fxfzypg.modules.rating.library.service.cache.KpExamScoringDbCacheService;
import com.css.fxfzypg.modules.rating.task.dao.*;
import com.css.fxfzypg.modules.rating.task.model.dto.*;
import com.css.fxfzypg.modules.rating.task.model.entity.*;
import com.css.fxfzypg.modules.rating.task.model.vo.*;
import com.css.fxfzypg.modules.rating.thread.BizThreadPoolManage;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.FieldHistoryUploadReport;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.HistoryUploadReport;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportManagementService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.SamplingSurveyReportService2;
import com.css.fxfzypg.modules.surveytaskmanage.entity.FieldSurveyTaskEntity;
import com.css.fxfzypg.modules.surveytaskmanage.service.FieldSurveyTaskService;
import com.css.fxfzypg.modules.system.service.UserCacheService;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.impl.SysAreaCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考评任务管理服务
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class KpRatingTaskService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    KpRatingTaskRepository kpRatingTaskRepository;
    @Autowired
    KpRatingTaskYpgTaskRepository kpRatingTaskYpgTaskRepository;
    @Autowired
    KpRatingTaskAreaRepository kpRatingTaskAreaRepository;
    @Autowired
    GroupService groupService;
    @Autowired
    private SUserService sUserService;
    @Autowired
    KpRatingTaskProgressRepository kpRatingTaskProgressRepository;
    public static final String CURR_USER_LATEST_CREATING_KP_TASK = "ypg:userLatestCreatingKpTask";
    private static final String KP_TASK_SYSTEM_SCORE_SCHEDULE = "kpTaskSystemScoreSchedule";
    private static final String KP_PROVINCE_SYSTEM_SCORE_SCHEDULE = "kpProvinceSystemScoreSchedule";
    @Autowired
    private SysAreaService sysAreaService;
    @Autowired
    private SysAreaCacheService sysAreaCacheService;
    // 考评库
    @Autowired
    private KpExamScoringDbService kpExamScoringDbService;
    @Autowired
    private KpExamScoringDbCacheService kpExamScoringDbCacheService;
    @Autowired
    private KpExamScoringDbIndex3Repository kpExamScoringDbIndex3Repository;
    @Autowired
    KpRatingTaskIndex3ScoreExpertRepository kpRatingTaskIndex3ScoreExpertRepository;
    @Autowired
    KpRatingTaskIndex3ScoreRepository kpRatingTaskIndex3ScoreRepository;
    @Autowired
    PreAssessTaskService preAssessTaskService;
    @Autowired
    KpExamScoringDbIndex2Repository kpExamScoringDbIndex2Repository;
    @Autowired
    KpRatingTaskItemScoreRepository kpRatingTaskItemScoreRepository;
    @Autowired
    KpExpertRatingService kpExpertRatingService;
    @Autowired
    KpRatingTaskExpertDao kpRatingTaskExpertDao;
    @Autowired
    KpRatingTaskExpertScoreProgressDao kpRatingTaskExpertScoreProgressDao;
    @Autowired
    MessageService messageService;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    FieldSurveyTaskService fieldSurveyTaskService;
    @Autowired
    private ReportManagementService reportManagementService;
    @Autowired
    private SamplingSurveyReportService2 samplingSurveyReportService;
    @Autowired
    RunSystemScoreService runSystemScoreService;



    @Autowired
    private KpRatingTaskService kpRatingTaskService;
    /**
     * 查询用户最新未保存的考评任务缓存
     *
     * @param currUid
     * @return
     */
    public NewKpTaskDto getLatestUnsaveKpTaskFromCache(String currUid) {
        HashOperations<String, String, NewKpTaskDto> hashOps = redisTemplate.opsForHash();
        NewKpTaskDto newKpTaskDto = hashOps.get(CURR_USER_LATEST_CREATING_KP_TASK, currUid);
        if (newKpTaskDto == null) {
            newKpTaskDto = new NewKpTaskDto();
            return newKpTaskDto;
        }
        GroupEntity groupEntity = groupService.getById(newKpTaskDto.getExpertGroupId());
        if (groupEntity != null) {
            newKpTaskDto.setExpertGroupName(groupEntity.getGroupName());
        }
        newKpTaskDto.getTaskList().forEach(o -> {
            o.setYpgName(Optional.ofNullable(preAssessTaskService.getById(o.getYpgId())).map(PreAssessTaskEntity::getTaskName).orElse(null));
            o.setXcdcName(Optional.ofNullable(fieldSurveyTaskService.getById(o.getXcdcId())).map(FieldSurveyTaskEntity::getTaskName).orElse(null));
            if (o.getProvinceIdList() != null) {
                Set<String> set = new HashSet<>();
                for (String id : o.getProvinceIdList()) {
                    set.add(sysAreaCacheService.getAreaNameByAreaId(id));
                }
                o.setProvinceNames(StringUtils.join(set, "、"));
            }
            o.setJbReportName(Optional.ofNullable(reportManagementService.getHistoryById(o.getJbReportId())).map(HistoryUploadReport::getReportName).orElse(null));
            o.setXbReportName(Optional.ofNullable(reportManagementService.getHistoryById(o.getXbReportId())).map(HistoryUploadReport::getReportName).orElse(null));
            o.setXcdcReportName(Optional.ofNullable(samplingSurveyReportService.getHistoryById(o.getXcdcReportId())).map(FieldHistoryUploadReport::getReportName).orElse(null));
        });
        return newKpTaskDto;
    }

    public void saveLatestUnsaveTaskToCache(String currUid, NewKpTaskDto latestCreateKpTaskFromCache) {
        HashOperations<String, String, NewKpTaskDto> hashOps = redisTemplate.opsForHash();
        hashOps.put(CURR_USER_LATEST_CREATING_KP_TASK, currUid, latestCreateKpTaskFromCache);
    }

    public void insertGlTask4Update(UpdateKpTaskDto dto, String currUid, KpRatingTask kpRatingTask) {
        List<KpRatingTaskYpgTask> glTasks = new ArrayList<>();
        List<KpRatingTaskArea> areaList = new ArrayList<>();
        Map<String, NewTaskYpgTaskDto> glTaskCacheMap = getUnsaveGlTaskCacheToMap(currUid);
        for (NewTaskYpgTaskDto newTaskYpgTaskDto : dto.getTaskList()) {
            KpRatingTaskYpgTask kpRatingTaskYpgTask = new KpRatingTaskYpgTask();
            kpRatingTaskYpgTask.setId(IdUtil.simpleUUID());
            kpRatingTaskYpgTask.setYpgTaskId(newTaskYpgTaskDto.getYpgId());
            kpRatingTaskYpgTask.setJbReportId(newTaskYpgTaskDto.getJbReportId());
            kpRatingTaskYpgTask.setXbReportId(newTaskYpgTaskDto.getXbReportId());
            kpRatingTaskYpgTask.setXcdcReportId(newTaskYpgTaskDto.getXcdcReportId());
            kpRatingTaskYpgTask.setXcdcTaskId(newTaskYpgTaskDto.getXcdcId());
            kpRatingTaskYpgTask.setKrtId(kpRatingTask.getId());
            NewTaskYpgTaskDto newTaskYpgTaskDtoCacheDto = glTaskCacheMap.get(newTaskYpgTaskDto.getId());
            if (newTaskYpgTaskDtoCacheDto != null) {
                kpRatingTaskYpgTask.setCreateTime(newTaskYpgTaskDtoCacheDto.getCreateTime());
            } else {
                kpRatingTaskYpgTask.setCreateTime(new Date());
            }
            glTasks.add(kpRatingTaskYpgTask);
            PreAssessTaskEntity ypgTask = preAssessTaskService.getById(newTaskYpgTaskDto.getYpgId());
            // 保存区域信息
            newTaskYpgTaskDto.getProvinceIdList().forEach(provinceId -> {
                KpRatingTaskArea kpRatingTaskArea = new KpRatingTaskArea();
                kpRatingTaskArea.setId(IdUtil.simpleUUID());
                kpRatingTaskArea.setProvinceId(provinceId);
                kpRatingTaskArea.setKrtytId(kpRatingTaskYpgTask.getId());
                kpRatingTaskArea.setArea(Optional.ofNullable(ypgTask).map(y -> new BigDecimal(y.getTaskArea())).orElse(BigDecimal.ZERO));
                kpRatingTaskArea.setAreaRatio(BigDecimal.ZERO);
                areaList.add(kpRatingTaskArea);
            });
        }
        kpRatingTaskYpgTaskRepository.batchSave(glTasks);
        kpRatingTaskAreaRepository.batchSave(areaList);
    }

    public void insertGlTask4Update(NewKpTaskDto dto, String currUid, KpRatingTask kpRatingTask) {
        List<KpRatingTaskYpgTask> glTasks = new ArrayList<>();
        List<KpRatingTaskArea> areaList = new ArrayList<>();
        Map<String, NewTaskYpgTaskDto> glTaskCacheMap = getUnsaveGlTaskCacheToMap(currUid);
        for (NewTaskYpgTaskDto newTaskYpgTaskDto : dto.getTaskList()) {
            KpRatingTaskYpgTask kpRatingTaskYpgTask = new KpRatingTaskYpgTask();
            kpRatingTaskYpgTask.setId(IdUtil.simpleUUID());
            kpRatingTaskYpgTask.setYpgTaskId(newTaskYpgTaskDto.getYpgId());
            kpRatingTaskYpgTask.setJbReportId(newTaskYpgTaskDto.getJbReportId());
            kpRatingTaskYpgTask.setXbReportId(newTaskYpgTaskDto.getXbReportId());
            kpRatingTaskYpgTask.setXcdcReportId(newTaskYpgTaskDto.getXcdcReportId());
            kpRatingTaskYpgTask.setXcdcTaskId(newTaskYpgTaskDto.getXcdcId());
            kpRatingTaskYpgTask.setKrtId(kpRatingTask.getId());
            NewTaskYpgTaskDto newTaskYpgTaskDtoCacheDto = glTaskCacheMap.get(newTaskYpgTaskDto.getId());
            if (newTaskYpgTaskDtoCacheDto != null) {
                kpRatingTaskYpgTask.setCreateTime(newTaskYpgTaskDtoCacheDto.getCreateTime());
            } else {
                kpRatingTaskYpgTask.setCreateTime(new Date());
            }
            glTasks.add(kpRatingTaskYpgTask);
            PreAssessTaskEntity ypgTask = preAssessTaskService.getById(newTaskYpgTaskDto.getYpgId());
            // 保存区域信息
            newTaskYpgTaskDto.getProvinceIdList().forEach(provinceId -> {
                KpRatingTaskArea kpRatingTaskArea = new KpRatingTaskArea();
                kpRatingTaskArea.setId(IdUtil.simpleUUID());
                kpRatingTaskArea.setProvinceId(provinceId);
                kpRatingTaskArea.setKrtytId(kpRatingTaskYpgTask.getId());
                kpRatingTaskArea.setArea(Optional.ofNullable(ypgTask).map(y -> new BigDecimal(y.getTaskArea())).orElse(BigDecimal.ZERO));
                kpRatingTaskArea.setAreaRatio(BigDecimal.ZERO);
                areaList.add(kpRatingTaskArea);
            });
        }
        kpRatingTaskYpgTaskRepository.batchSave(glTasks);
        kpRatingTaskAreaRepository.batchSave(areaList);
    }

    /**
     * 获取未保存的关联任务，然后转为map返回，id为key，entity为value
     *
     * @param currUid
     * @return
     */
    private Map<String, NewTaskYpgTaskDto> getUnsaveGlTaskCacheToMap(String currUid) {
        NewKpTaskDto latestUnsaveKpTaskFromCache = getLatestUnsaveKpTaskFromCache(currUid);
        List<NewTaskYpgTaskDto> taskList = latestUnsaveKpTaskFromCache.getTaskList();
        Map<String, NewTaskYpgTaskDto> glTaskCacheMap = taskList.stream().collect(Collectors.toMap(NewTaskYpgTaskDto::getId, v -> v, (k1, k2) -> k2));
        return glTaskCacheMap;
    }

    /**
     * 考评任务管理，新建环节，查询详情接口
     *
     * @param taskId 考评任务id
     * @return
     */
    public KpTaskManageNewStatusDetailsVo getById(String taskId) {
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(taskId);
        if (kpRatingTask == null) {
            return null;
        }
        KpTaskManageNewStatusDetailsVo vo = new KpTaskManageNewStatusDetailsVo();
        vo.setId(kpRatingTask.getId());
        vo.setName(kpRatingTask.getName());
        vo.setKesdId(kpRatingTask.getKesdId());
        vo.setKesdName(Optional.ofNullable(kpExamScoringDbCacheService.getById(kpRatingTask.getKesdId())).map(KpExamScoringDb::getName).orElse(null));
        vo.setExpertGroupId(kpRatingTask.getExpertGroupId());
        vo.setExpertGroupName(Optional.ofNullable(groupService.getById(kpRatingTask.getExpertGroupId())).map(GroupEntity::getGroupName).orElse(null));
        vo.setEndDate(kpRatingTask.getEndDate());
        vo.setProgressList(this.getProgressList(taskId));
        vo.setTaskList(this.getGlTaskList(taskId));
/*        if (vo.getProgressList().size()==5){
            //||vo.getProgressList().size()==4
            vo.setAreaList(this.getAreaListFive(kpRatingTask));
        }else {

        }*/
        vo.setAreaList(this.getAreaList(kpRatingTask));
        vo.setIsRunAreaRatio(kpRatingTask.getIsRunAreaRatio());
        List<KpTaskManageNewStatusGlTaskDetailsVo> glTaskList = getGlTaskList(taskId);
        boolean mark=false;
        for (KpTaskManageNewStatusGlTaskDetailsVo kpVO : glTaskList) {
            if (kpVO.getFlag()){
                mark=true;
            }
        }
        vo.setMark(mark);
        vo.setShowOrNot(false);
        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.selectByKrtId(taskId);
        Map<String, List<KpRatingTaskArea>> map = new HashMap<>();
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
            if (map.get(kpRatingTaskArea.getProvinceId()) == null) {
                List<KpRatingTaskArea> list = new ArrayList<>();
                list.add(kpRatingTaskArea);
                map.put(kpRatingTaskArea.getProvinceId(), list);
            } else {
                map.get(kpRatingTaskArea.getProvinceId()).add(kpRatingTaskArea);
            }
        }
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
            List<KpRatingTaskArea> kpRatingTaskAreas = map.get(kpRatingTaskArea.getProvinceId());
            if (kpRatingTaskAreas.size()>1){
                vo.setShowOrNot(true);
            }
        }
        return vo;
    }

    private List<KpTaskManageNewStatusGlAreaDetailsVo> getAreaListFive(KpRatingTask kpRatingTask) {
        List<KpTaskManageNewStatusGlAreaDetailsVo> kpTaskManageNewStatusGlAreaDetailsVos = kpRatingTaskYpgTaskRepository.getKpTaskManagerGlTaskList(kpRatingTask.getId());
        Collections.reverse(kpTaskManageNewStatusGlAreaDetailsVos);
        Map<String, KpTaskManageNewStatusGlAreaDetailsVo> areaVoMap = new HashMap<>();
        for (KpTaskManageNewStatusGlAreaDetailsVo currVo : kpTaskManageNewStatusGlAreaDetailsVos) {
            List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(currVo.getKrtytId());
            Integer exportNum= kpRatingTaskIndex3ScoreExpertRepository.getExportNumByKrtytId(currVo.getKrtytId());
            BigDecimal exportLastScore = kpRatingTaskIndex3ScoreExpertRepository.getByKrtytId(currVo.getKrtytId());
            for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
                KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());
                List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytId(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId());
                //分数/人数 1个人不用管  2个人减去一个平均值3个人减去2*平均值
                if (PlatformObjectUtils.isNotEmpty(index3ExpertList)) {
                    if (currVo.getExportScore() == null) {
                        currVo.setExportScore(BigDecimal.ZERO);
                    }
                    currVo.setExportScore(currVo.getExportScore().add(BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(i3 -> i3.getScore().doubleValue()).sum())));
                }
            }
//            List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKrtytId(currVo.getKrtytId());
            if (currVo.getSystemScore() == null) currVo.setSystemScore(BigDecimal.ZERO);
            if (currVo.getExportScore() == null) currVo.setExportScore(BigDecimal.ZERO);
            if (currVo.getLastScore() == null) currVo.setLastScore(BigDecimal.ZERO);
            if (currVo.getTotalScore() == null) currVo.setTotalScore(BigDecimal.ZERO);
            KpTaskManageNewStatusGlAreaDetailsVo prevVo = areaVoMap.get(currVo.getProvinceId());
            if (prevVo != null) {
                prevVo.setYpgTaskNames(prevVo.getYpgTaskNames() + "、" + currVo.getYpgTaskNames());
                prevVo.setSystemScore(currVo.getSystemScore().add(prevVo.getSystemScore()));
                prevVo.setTotalScore(currVo.getTotalScore().add(prevVo.getTotalScore()));
                areaVoMap.put(prevVo.getProvinceId(), prevVo);
              //  if (currVo.getLastScore() != null) currVo.setLastScore(exportLastScore.add(prevVo.getSystemScore()));
            } else {
                currVo.setProvince(sysAreaCacheService.getAreaNameByAreaId(currVo.getProvinceId()));
                // 查询专家打分进程
                String exportScoreProgress = getExportScoreProgress(kpRatingTask, kpTaskManageNewStatusGlAreaDetailsVos, currVo);
                currVo.setExportScoreProgress(exportScoreProgress);

                if (exportNum==1){
                    exportLastScore=exportLastScore;
                    currVo.setExportScore(exportLastScore.divide(BigDecimal.valueOf(exportNum)));
                    currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
                }else if (exportNum==0){
                    exportLastScore=exportLastScore;
                    currVo.setExportScore(exportLastScore.divide(BigDecimal.valueOf(1)));
                    currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
                }else {
                    currVo.setExportScore(exportLastScore.divide(BigDecimal.valueOf(exportNum)));
                  //  exportLastScore=exportLastScore.subtract(exportLastScore.multiply(new BigDecimal(exportNum-1).setScale(2,RoundingMode.HALF_UP).divide(new BigDecimal(exportNum),2,RoundingMode.HALF_UP))).setScale(2, RoundingMode.HALF_UP);
                   // currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()).subtract(exportLastScore));
                    currVo.setLastScore(currVo.getTotalScore().subtract(exportLastScore));
                }
             //   currVo.setTotalScore(currVo.getSystemScore().add(currVo.getExportScore()));
                currVo.setTotalScore(currVo.getSystemScore().add(exportLastScore.divide(BigDecimal.valueOf(kpRatingTaskExpertScoreProgressDao.getExportComNumByKrtytId(currVo.getKrtytId())))));
                currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
               // currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
              //  currVo.setLastScore(exportLastScore);
                areaVoMap.put(currVo.getProvinceId(), currVo);
            }
        }
        return new ArrayList<>(areaVoMap.values());
    }

    /**
     * 构建区域列表
     *
     * @param kpRatingTask
     * @return
     */
    private List<KpTaskManageNewStatusGlAreaDetailsVo> getAreaList(KpRatingTask kpRatingTask) {
        List<KpTaskManageNewStatusGlAreaDetailsVo> kpTaskManageNewStatusGlAreaDetailsVos = kpRatingTaskYpgTaskRepository.getKpTaskManagerGlTaskList(kpRatingTask.getId());
        Collections.reverse(kpTaskManageNewStatusGlAreaDetailsVos);
        Map<String, KpTaskManageNewStatusGlAreaDetailsVo> areaVoMap = new HashMap<>();
        Map<String, List<KpTaskManageNewStatusGlAreaDetailsVo>> collect = kpTaskManageNewStatusGlAreaDetailsVos.stream().collect(Collectors.groupingBy(KpTaskManageNewStatusGlAreaDetailsVo::getProvinceId));
        collect.forEach((k,v)->{
            BigDecimal exprotScoreAvg=BigDecimal.ZERO;
            BigDecimal exNum=BigDecimal.ZERO;
            for (KpTaskManageNewStatusGlAreaDetailsVo currVo : v) {
                List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(currVo.getKrtytId());
                for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
                    // KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());
                    // List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytId(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId());
                    //每一个预评估任务的专家评分
                    BigDecimal exportTSocre = kpRatingTaskIndex3ScoreExpertRepository.getByKrtytId(kpRatingTaskExpertScoreProgress.getKrtytId());
                    BigDecimal areaRatio= kpRatingTaskAreaRepository.getAreaRatioByKrtytId(kpRatingTaskExpertScoreProgress.getKrtytId());
                    exprotScoreAvg=exprotScoreAvg.add(exportTSocre.multiply(areaRatio));
                    //  List<KpRatingTaskIndex3ScoreExpert> index3ExpertListAvg = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytIdAvg(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId());
                    exNum= BigDecimal.valueOf(kpRatingTaskExpertScoreProgressDao.getExportComNumByKrtytId(currVo.getKrtytId()));
                    if (PlatformObjectUtils.isNotEmpty(exportTSocre)) {
                        if (currVo.getExportScore() == null) {
                            currVo.setExportScore(BigDecimal.ZERO);
                        }
                        //currVo.setExportScore(currVo.getExportScore().add(BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(i3 -> i3.getScore().doubleValue()).sum())));
                        currVo.setExportScore(exportTSocre.multiply(areaRatio).divide(exNum));
                        //   exprotScoreAvg=exprotScoreAvg.add(BigDecimal.valueOf(index3ExpertListAvg.stream().mapToDouble(i3 -> i3.getScore().doubleValue()).sum()));
                    }
                    //  exprotScoreAvg=exprotScoreAvg.divide(exNum);
                }
//            List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKrtytId(currVo.getKrtytId());
                if (currVo.getSystemScore() == null) currVo.setSystemScore(BigDecimal.ZERO);
                if (currVo.getExportScore() == null) currVo.setExportScore(BigDecimal.ZERO);
                if (currVo.getLastScore() == null) currVo.setLastScore(BigDecimal.ZERO);
                if (currVo.getTotalScore() == null) currVo.setTotalScore(BigDecimal.ZERO);

                KpTaskManageNewStatusGlAreaDetailsVo prevVo = areaVoMap.get(currVo.getProvinceId());
                if (prevVo != null) {
                    prevVo.setYpgTaskNames(prevVo.getYpgTaskNames() + "、" + currVo.getYpgTaskNames());
                    prevVo.setSystemScore(currVo.getSystemScore().add(prevVo.getSystemScore()).setScale(1,RoundingMode.HALF_UP));
                    if (exNum.compareTo(BigDecimal.ZERO)==0){
                        exNum=BigDecimal.ONE;
                    }
                    if (exNum==BigDecimal.ONE){
                        prevVo.setExportScore(exprotScoreAvg.divide(exNum).setScale(1,RoundingMode.HALF_UP));

                    }else {
                        prevVo.setExportScore(exprotScoreAvg.divide(exNum).divide(BigDecimal.valueOf(v.size())).setScale(1,RoundingMode.HALF_UP));
                    }
                    // prevVo.setTotalScore(currVo.getTotalScore().add(prevVo.getTotalScore()));
                 //   prevVo.setTotalScore(currVo.getSystemScore().add(prevVo.getExportScore()));
                    prevVo.setTotalScore(currVo.getSystemScore().add(currVo.getExportScore()).add(prevVo.getExportScore().add(prevVo.getSystemScore())));
                    areaVoMap.put(prevVo.getProvinceId(), prevVo);
                } else {
                    currVo.setProvince(sysAreaCacheService.getAreaNameByAreaId(currVo.getProvinceId()));
                    // 查询专家打分进程
                    String exportScoreProgress = getExportScoreProgress(kpRatingTask, kpTaskManageNewStatusGlAreaDetailsVos, currVo);
                    currVo.setExportScoreProgress(exportScoreProgress);
                    currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
                    if (exNum.compareTo(BigDecimal.ZERO) == 0) {
                        exNum = BigDecimal.ONE;
                    }
                  //  currVo.setExportScore(exprotScoreAvg.divide(exNum));
                    currVo.setTotalScore(currVo.getSystemScore().add(currVo.getExportScore()));

                    areaVoMap.put(currVo.getProvinceId(), currVo);
                }
            }
            areaVoMap.get(k).setTotalScore(areaVoMap.get(k).getExportScore().add(areaVoMap.get(k).getSystemScore()));
        });
   /*     for (KpTaskManageNewStatusGlAreaDetailsVo currVo : kpTaskManageNewStatusGlAreaDetailsVos) {
            areaVoMap.put(currVo.getProvinceId(),currVo);
            BigDecimal exprotScoreAvg=BigDecimal.ZERO;
            BigDecimal exNum=BigDecimal.ZERO;
            BigDecimal xtScore=BigDecimal.ZERO;
            List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(currVo.getKrtytId());
            for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
               // KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());
               // List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytId(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId());
                //每一个预评估任务的专家评分
                BigDecimal exportTSocre = kpRatingTaskIndex3ScoreExpertRepository.getByKrtytId(kpRatingTaskExpertScoreProgress.getKrtytId());
                BigDecimal areaRatio= kpRatingTaskAreaRepository.getAreaRatioByKrtytId(kpRatingTaskExpertScoreProgress.getKrtytId());
                exprotScoreAvg=exprotScoreAvg.add(exportTSocre.multiply(areaRatio));
              //  List<KpRatingTaskIndex3ScoreExpert> index3ExpertListAvg = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytIdAvg(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId());
                exNum= BigDecimal.valueOf(kpRatingTaskExpertScoreProgressDao.getExportComNumByKrtytId(currVo.getKrtytId()));
                if (PlatformObjectUtils.isNotEmpty(exportTSocre)) {
                    if (currVo.getExportScore() == null) {
                        currVo.setExportScore(BigDecimal.ZERO);
                    }
                    //currVo.setExportScore(currVo.getExportScore().add(BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(i3 -> i3.getScore().doubleValue()).sum())));
                    currVo.setExportScore(exportTSocre.multiply(areaRatio).divide(exNum));
                 //   exprotScoreAvg=exprotScoreAvg.add(BigDecimal.valueOf(index3ExpertListAvg.stream().mapToDouble(i3 -> i3.getScore().doubleValue()).sum()));
                }
              //  exprotScoreAvg=exprotScoreAvg.divide(exNum);
            }
//            List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKrtytId(currVo.getKrtytId());
            if (currVo.getSystemScore() == null) currVo.setSystemScore(BigDecimal.ZERO);
            if (currVo.getExportScore() == null) currVo.setExportScore(BigDecimal.ZERO);
            if (currVo.getLastScore() == null) currVo.setLastScore(BigDecimal.ZERO);
            if (currVo.getTotalScore() == null) currVo.setTotalScore(BigDecimal.ZERO);

            KpTaskManageNewStatusGlAreaDetailsVo prevVo = areaVoMap.get(currVo.getProvinceId());
            if (prevVo != null) {
                prevVo.setYpgTaskNames(prevVo.getYpgTaskNames() + "、" + currVo.getYpgTaskNames());
                prevVo.setSystemScore(currVo.getSystemScore().add(prevVo.getSystemScore()));
                if (exNum.compareTo(BigDecimal.ZERO)==0){
                    exNum=BigDecimal.ONE;
                }
                prevVo.setExportScore(exprotScoreAvg.divide(exNum.multiply(BigDecimal.valueOf(Double.valueOf("2")))));
               // prevVo.setTotalScore(currVo.getTotalScore().add(prevVo.getTotalScore()));
                prevVo.setTotalScore(currVo.getTotalScore().add(prevVo.getExportScore()));
                areaVoMap.put(prevVo.getProvinceId(), prevVo);
            } else {
                currVo.setProvince(sysAreaCacheService.getAreaNameByAreaId(currVo.getProvinceId()));
                // 查询专家打分进程
                String exportScoreProgress = getExportScoreProgress(kpRatingTask, kpTaskManageNewStatusGlAreaDetailsVos, currVo);
                currVo.setExportScoreProgress(exportScoreProgress);
                currVo.setLastScore(kpRatingTaskItemScoreRepository.sumScoreByProvinceIdAndKrtId(currVo.getProvinceId(), kpRatingTask.getId()));
                if (exNum.compareTo(BigDecimal.ZERO)==0){
                    exNum=BigDecimal.ONE;
                }
                currVo.setExportScore(exprotScoreAvg.divide(exNum.multiply(BigDecimal.valueOf(Double.valueOf("2")))));
                currVo.setTotalScore(currVo.getSystemScore().add(currVo.getExportScore()));

                areaVoMap.put(currVo.getProvinceId(), currVo);
            }
        }*/
        return new ArrayList<>(areaVoMap.values());
    }

    /**
     * 查询专家打分进程
     *
     * @param kpRatingTask
     * @param kpTaskManageNewStatusGlAreaDetailsVos
     * @param nextVo
     * @return
     */
    private String getExportScoreProgress(KpRatingTask kpRatingTask, List<KpTaskManageNewStatusGlAreaDetailsVo> kpTaskManageNewStatusGlAreaDetailsVos, KpTaskManageNewStatusGlAreaDetailsVo nextVo) {
        List<String> currProvGlTaskIdList = kpTaskManageNewStatusGlAreaDetailsVos.stream().filter(o -> o.getProvinceId().equals(nextVo.getProvinceId())).map(KpTaskManageNewStatusGlAreaDetailsVo::getKrtytId).collect(Collectors.toList());
        GroupMemberVo groupMemberVo = groupService.findById(kpRatingTask.getExpertGroupId());
        if (groupMemberVo == null) {
            return null;
        }
        Integer submittedNum = kpExpertRatingService.countSubmittedNum(currProvGlTaskIdList);
        List<UserEntity> expertlist = groupMemberVo.getExpertlist();
        if (expertlist == null) {
            expertlist = new ArrayList<>();
        }
        return submittedNum + "/" + expertlist.size();
    }

    private List<KpTaskManageNewStatusGlTaskDetailsVo> getGlTaskList(String krtId) {
        List<KpTaskManageNewStatusGlTaskDetailsVo> glTaskList = kpRatingTaskYpgTaskRepository.getKpGlTaskList(krtId);
        if (glTaskList == null) {
            return null;
        }
        return glTaskList.stream().peek(o -> {
            List<KpRatingTaskArea> areaList = getKpRatingTaskAreas(o.getId());
            o.setProvinceIdList(Optional.ofNullable(areaList).map(a -> a.stream().map(KpRatingTaskArea::getProvinceId).collect(Collectors.toList())).orElse(new ArrayList<>()));
            o.setProvinceNames(StringUtils.join(o.getProvinceIdList().stream().map(p -> sysAreaCacheService.getAreaNameByAreaId(p)).collect(Collectors.toSet()), "、"));
            o.setJbReportName(Optional.ofNullable(reportManagementService.getHistoryById(o.getJbReportId())).map(HistoryUploadReport::getReportName).orElse(null));
            o.setXbReportName(Optional.ofNullable(reportManagementService.getHistoryById(o.getXbReportId())).map(HistoryUploadReport::getReportName).orElse(null));
            o.setXcdcReportName(Optional.ofNullable(samplingSurveyReportService.getHistoryById(o.getXcdcReportId())).map(FieldHistoryUploadReport::getReportName).orElse(null));
            o.setYpgName(Optional.ofNullable(preAssessTaskService.getById(o.getYpgId())).map(PreAssessTaskEntity::getTaskName).orElse(null));
            o.setXcdcName(Optional.ofNullable(fieldSurveyTaskService.getById(o.getXcdcId())).map(FieldSurveyTaskEntity::getTaskName).orElse(null));
            o.setShow(false);
            List<PreAssessTaskEntity> subTask = preAssessTaskService.getSubTask(o.getYpgId());
            if (PlatformObjectUtils.isEmpty(subTask)) {
                o.setFlag(false);
            } else {
                o.setFlag(true);
            }
        }).collect(Collectors.toList());
    }

    private List<KpRatingTaskArea> getKpRatingTaskAreas(String id) {
        KpRatingTaskArea kpRatingTaskArea = new KpRatingTaskArea();
        kpRatingTaskArea.setKrtytId(id);
        return kpRatingTaskAreaRepository.list(kpRatingTaskArea);
    }

    /**
     * 根据考评任务的进度信息
     *
     * @param krtId
     * @return
     */
    private List<KpRatingTaskProgress> getProgressList(String krtId) {
        KpRatingTaskProgress kpRatingTaskProgressParam = new KpRatingTaskProgress();
        kpRatingTaskProgressParam.setKrtId(krtId);
        return kpRatingTaskProgressRepository.list(kpRatingTaskProgressParam);
    }

    /**
     * 查询考评任务
     *
     * @param kpRatingTask
     * @return
     */
    public List<KpRatingTask> list(KpRatingTask kpRatingTask) {
        return kpRatingTaskRepository.list(kpRatingTask);
    }

    /**
     * 删除考评任务
     *
     * @param taskId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteKpTask(String taskId, String uid) {
        Date delTime = new Date();
        kpRatingTaskRepository.deleteById(taskId, uid, delTime);
    }

    /**
     * 修改考评任务
     *
     * @param currUid
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateKpTask(String currUid, UpdateKpTaskDto dto) {
        KpRatingTask kpRatingTask = new KpRatingTask();
        kpRatingTask.setUpdateUser(currUid);
        kpRatingTask.setUpdateTime(new Date());
        kpRatingTask.setId(dto.getKpTaskId());
        kpRatingTask.setName(dto.getName());
        kpRatingTask.setKesdId(dto.getKesdId());
        kpRatingTask.setExpertGroupId(dto.getExpertGroupId());
        kpRatingTask.setEndDate(dto.getEndDate());
        kpRatingTaskRepository.updateById(kpRatingTask);
        kpRatingTaskYpgTaskRepository.deleteByKrtId(kpRatingTask.getId());
        this.insertGlTask4Update(dto, currUid, kpRatingTask);
    }

    /**
     * 查询得分详情
     *
     * @param provinceId 省id
     * @param krtId
     * @return
     */
    public List<KpIndexScoreDetailsVo> getGlTaskScoreDetails(String provinceId, String krtId) {
        // 查询某省份下的的所有关联任务
        List<KpRatingTaskYpgTask> taskList = kpRatingTaskYpgTaskRepository.getByProvinceId(provinceId, krtId);
        if (taskList == null) {
            log.warn("当前区域下找不到预评估任务");
            return null;
        }
        List<KpIndexScoreDetailsVo> resList = new ArrayList<>();
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        if (kpRatingTask == null) {
            throw new RuntimeException("考评任务id错误");
        }
        // 查询指标库下的指标
        List<KpExamScoringDbIndex1Vo> kpExamScoringDbIndex1VoList = kpExamScoringDbService.getIndex(kpRatingTask.getKesdId());
        for (KpRatingTaskYpgTask task : taskList) {
            List<KpIndexScoreDetailsVo.AreaScore> totalSystemScore = new ArrayList<>();
            BigDecimal totalExpertScore = BigDecimal.ZERO;
            List<KpIndexScoreVo> indexList = new ArrayList<>();
            // 指标库下没有指标，构建任务名称和空的指标列表vo
            if (kpExamScoringDbIndex1VoList == null) {
                resList.add(buildEmptyIndexScoreDetailsVo(task));
                continue;
            }
            // 根据指标构建vo
            for (KpExamScoringDbIndex1Vo index1 : kpExamScoringDbIndex1VoList) {
                if (index1.getChildren() == null) {
                    indexList.add(buildEmptyIndexScoreVoByIndex1(index1));
                    continue;
                }
                BigDecimal index1Score = kpExamScoringDbIndex3Repository.sumScoreByKesdi1Id(index1.getId());
                for (KpExamScoringDbIndex2Vo index2 : index1.getChildren()) {
                    if (index2.getChildren() == null) {
                        KpIndexScoreVo kpIndexScoreVo = buildEmptyIndexScoreVoByIndex2(index1, index2);
                        indexList.add(kpIndexScoreVo);
                        continue;
                    }
                    double index2Score = index2.getChildren().stream().mapToDouble(o -> o.getScore().doubleValue()).sum();
                    for (KpExamScoringDbIndex3Vo index3 : index2.getChildren()) {
                        KpIndexScoreVo kpIndexScoreVo = new KpIndexScoreVo();
                        List<KpIndexScoreVo.SystemScore> systemScoreList = kpIndexScoreVo.getSystemScoreList();
                        KpIndex3Data kpIndex3Data = index3.getKpIndex3Data();
                        // get expert score
//                        BigDecimal expertScore = kpRatingTaskIndex3ScoreExpertRepository.sumScoreByKesdi3IdAndKrtytId(index3.getId(), task.getId());
                        BigDecimal expertScore = BigDecimal.ZERO;
                        // TODO 查询提交状态的分数
                        List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(task.getId());







                        for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
                            KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());


                            List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByKrtytIdAndKesdi3Id(kpRatingTaskExpertScoreProgress.getKrtytId(), index3.getId());
                            //   Integer num=kpRatingTaskIndex3ScoreExpertRepository.getExportNumByKrtId(krtId);

                            if (PlatformObjectUtils.isNotEmpty(index3ExpertList)) {
                                int i=0;
                                for (KpRatingTaskIndex3ScoreExpert kpRatingTaskIndex3ScoreExpert : index3ExpertList) {
                                    if (PlatformObjectUtils.isNotEmpty(kpRatingTaskIndex3ScoreExpert.getScore())){
                                        i++;
                                    }
                                }
                                expertScore = BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum()).divide(new BigDecimal(i),1);
                               // kpRatingTaskItemScoreRepository.updateLastScoreByKesdi2Id(index2.getId(),expertScore);
                            }
                          /*  List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytIdAndKesdi3Id(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId(), index3.getId());
                            if (index3ExpertList != null) {
                                expertScore = BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum());
                            }*/
                        }
//                        List<KpRatingTaskIndex3ScoreExpert> expertScoreList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKesdi3IdAndKrtytyId(index3.getId(), task.getId());
//                        if (expertScoreList != null) {
//                            expertScore = BigDecimal.valueOf(expertScoreList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum());
//                        }
                        // get system score list
                        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtytId(task.getId());
                        for (KpRatingTaskArea area : areaList) {
                            KpIndexScoreVo.SystemScore systemScoreVo = new KpIndexScoreVo.SystemScore();
                            systemScoreVo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
                            BigDecimal score = kpRatingTaskIndex3ScoreRepository.sumScoreByKesdi3IdAndKrtaId(index3.getId(), area.getId());
                            if (score == null) {
                                score = BigDecimal.ZERO;
                            }
                            systemScoreVo.setSystemScore(score);
                            systemScoreList.add(systemScoreVo);
                            boolean flag = false;
                            for (KpIndexScoreDetailsVo.AreaScore areaScore : totalSystemScore) {
                                if (areaScore.getProvinceName().equals(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()))) {
                                    areaScore.setTotalSystemScore(areaScore.getTotalSystemScore().add(score));
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) {
                                KpIndexScoreDetailsVo.AreaScore areaScore = new KpIndexScoreDetailsVo.AreaScore();
                                areaScore.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
                                areaScore.setTotalSystemScore(score);
                                totalSystemScore.add(areaScore);
                            }
                        }
                        // 计算系统得分和专家得分的总分数
                        totalExpertScore = totalExpertScore.add(expertScore == null ? BigDecimal.ZERO : expertScore);
                        kpIndexScoreVo.setIndex1Id(index1.getId());
                        kpIndexScoreVo.setIndex1Name(index1.getName());
                        kpIndexScoreVo.setIndex1Score(index1Score);
                        kpIndexScoreVo.setIndex2Id(index2.getId());
                        kpIndexScoreVo.setIndex2Name(index2.getName());
                        kpIndexScoreVo.setIndex2Score(BigDecimal.valueOf(index2Score));
                        kpIndexScoreVo.setIndex3Id(index3.getId());
                        kpIndexScoreVo.setKpIndex3Data(kpIndex3Data);
                        kpIndexScoreVo.setIndex3Score(index3.getScore());
                        kpIndexScoreVo.setIndex3Standard(index3.getIndexStandard());


                     //   kpRatingTaskService.getExpertScoreDetails(kesdi3Id, krtytId);
                        //现在应该用平均分
                        kpIndexScoreVo.setExpertScore(expertScore == null ? BigDecimal.ZERO : expertScore);
                        indexList.add(kpIndexScoreVo);
                    }
                }
            }
            BigDecimal finalTotalExpertScore = totalExpertScore;
            totalSystemScore.forEach(o -> {
                o.setTotalScore(finalTotalExpertScore.add(o.getTotalSystemScore()));
            });
            KpIndexScoreDetailsVo kpIndexScoreDetailsVo = new KpIndexScoreDetailsVo();
            kpIndexScoreDetailsVo.setYpgId(task.getYpgTaskId());
            kpIndexScoreDetailsVo.setKrtytId(task.getId());
            kpIndexScoreDetailsVo.setYpgName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(task.getId()));
            kpIndexScoreDetailsVo.setTotalExpertScore(totalExpertScore);
            kpIndexScoreDetailsVo.setAreaScoreList(totalSystemScore);
            kpIndexScoreDetailsVo.setIndexList(indexList);
            resList.add(kpIndexScoreDetailsVo);

            // TODO 测试用，提交代码注释这一段 ↓
//            KpIndexScoreDetailsVo kpIndexScoreDetailsVo1 = new KpIndexScoreDetailsVo();
//            BeanUtils.copyProperties(kpIndexScoreDetailsVo, kpIndexScoreDetailsVo1);
//            kpIndexScoreDetailsVo1.setYpgName("测试");
//            List<KpIndexScoreVo> indexList_ = new ArrayList<>();
//            for (KpIndexScoreVo kpIndexScoreVo : kpIndexScoreDetailsVo1.getIndexList()) {
//                KpIndexScoreVo vo1 = new KpIndexScoreVo();
//                BeanUtils.copyProperties(kpIndexScoreVo, vo1);
//                vo1.setExpertScore(BigDecimal.ONE);
//                indexList_.add(vo1);
//            }
//            kpIndexScoreDetailsVo1.setIndexList(indexList_);
//            resList.add(kpIndexScoreDetailsVo1);
            // TODO 测试用，提交代码注释这一段 ↑
        }
        return resList;
    }

    private static KpIndexScoreVo buildEmptyIndexScoreVoByIndex2(KpExamScoringDbIndex1Vo index1, KpExamScoringDbIndex2Vo index2) {
        KpIndexScoreVo kpIndexScoreVo = new KpIndexScoreVo();
        kpIndexScoreVo.setIndex1Id(index1.getId());
        kpIndexScoreVo.setIndex1Name(index1.getName());
        kpIndexScoreVo.setIndex1Score(index1.getScore());
        kpIndexScoreVo.setIndex2Id(index2.getId());
        kpIndexScoreVo.setIndex2Name(index2.getName());
        kpIndexScoreVo.setIndex2Score(index2.getScore());
        return kpIndexScoreVo;
    }

    private static KpIndexScoreVo buildEmptyIndexScoreVoByIndex1(KpExamScoringDbIndex1Vo kpExamScoringDbIndex1Vo) {
        KpIndexScoreVo kpIndexScoreVo = new KpIndexScoreVo();
        kpIndexScoreVo.setIndex1Id(kpExamScoringDbIndex1Vo.getId());
        kpIndexScoreVo.setIndex1Name(kpExamScoringDbIndex1Vo.getName());
        kpIndexScoreVo.setIndex1Score(kpExamScoringDbIndex1Vo.getScore());
        return kpIndexScoreVo;
    }

    private KpIndexScoreDetailsVo buildEmptyIndexScoreDetailsVo(KpRatingTaskYpgTask task) {
        KpIndexScoreDetailsVo kpIndexScoreDetailsVo = new KpIndexScoreDetailsVo();
        kpIndexScoreDetailsVo.setYpgId(task.getYpgTaskId());
        kpIndexScoreDetailsVo.setKrtytId(task.getId());
        kpIndexScoreDetailsVo.setYpgName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(task.getId()));
        kpIndexScoreDetailsVo.setTotalExpertScore(BigDecimal.ZERO);
        return kpIndexScoreDetailsVo;
    }

    /**
     * 查询专家打分信息
     *
     * @param kesdi3Id
     * @param krtytId
     * @return
     */
    public List<KpRatingTaskIndex3ScoreExpertVo> getExpertScoreDetails(String kesdi3Id, String krtytId) {
        KpRatingTaskYpgTask glTask = kpRatingTaskYpgTaskRepository.getById(krtytId);
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(glTask.getKrtId());
        GroupMemberVo groupMemberVo = groupService.findById(kpRatingTask.getExpertGroupId());
        List<KpRatingTaskIndex3ScoreExpertVo> vos = new ArrayList<>();
        for (UserEntity userEntity : groupMemberVo.getExpertlist()) {
            if (userEntity == null) {
                continue;
            }
            KpRatingTaskIndex3ScoreExpertVo vo = new KpRatingTaskIndex3ScoreExpertVo();
            vo.setExpertId(userEntity.getUuid());
            vo.setExpertName(userEntity.getRealName());
            KpRatingTaskExpertScoreProgress progress = kpRatingTaskExpertScoreProgressDao.getByExpertAndKrtytId(krtytId, userEntity.getUuid());
            //TODO 提交状态分数
            if (progress == null || progress.getStatus() == null) {
               // vo.setScore(BigDecimal.ZERO);
                vo.setScore(null);
            } else {
                if (progress.getStatus() == 0 || progress.getStatus() == 1) {
                    //vo.setScore(BigDecimal.ZERO);
                    vo.setScore(null);
                } else {
                    KpRatingTaskIndex3ScoreExpert k = kpRatingTaskIndex3ScoreExpertRepository.getByKesdi3IdAndExpertIdAndKrtytId(kesdi3Id, userEntity.getUuid(), krtytId);
                    if (k == null) {
                      //  vo.setScore(BigDecimal.ZERO);
                        vo.setScore(null);
                    } else {
                        BeanUtils.copyProperties(k, vo);
                    }
                }
            }
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 分发考评任务
     *
     * @param krtId
     */
    @Transactional(rollbackFor = Exception.class)
    public void distributionKpTask2Expert(String krtId, String distributeUid) {
        //  修改任务状态
        KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, 2);
        if (kpRatingTaskProgress == null) {
            kpRatingTaskProgress = new KpRatingTaskProgress();
            kpRatingTaskProgress.setId(IdUtil.simpleUUID());
            kpRatingTaskProgress.setStatus(2);
            kpRatingTaskProgress.setStatusTime(new Date());
            kpRatingTaskProgress.setKrtId(krtId);
            kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
        } else {
            return;
        }
        Date currTime = new Date();
        List<KpRatingTaskExpert> expertList = new ArrayList<>();
        List<KpRatingTaskExpertScoreProgress> progressList = new ArrayList<>();

        KpRatingTask task = kpRatingTaskRepository.getById(krtId);
        GroupMemberVo groupMemberVo = groupService.findById(task.getExpertGroupId());
        for (UserEntity userEntity : groupMemberVo.getExpertlist()) {
            if (userEntity == null) {
                continue;
            }
            //  专家表入库
            KpRatingTaskExpert kpRatingTaskExpert = new KpRatingTaskExpert();
            kpRatingTaskExpert.setId(IdUtil.simpleUUID());
            kpRatingTaskExpert.setExpertId(userEntity.getUuid());
            kpRatingTaskExpert.setKrtId(krtId);
            expertList.add(kpRatingTaskExpert);
            List<KpRatingTaskYpgTask> glTaskList = kpRatingTaskYpgTaskRepository.getByKryId(krtId);
            for (KpRatingTaskYpgTask glTask : glTaskList) {
                KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress = new KpRatingTaskExpertScoreProgress();
                kpRatingTaskExpertScoreProgress.setId(IdUtil.simpleUUID());
                kpRatingTaskExpertScoreProgress.setKrteId(kpRatingTaskExpert.getId());
                kpRatingTaskExpertScoreProgress.setExpertGroupId(task.getExpertGroupId());
                kpRatingTaskExpertScoreProgress.setKrtytId(glTask.getId());
                kpRatingTaskExpertScoreProgress.setStatus(KpExpertRatingStatus.UN_RATING.getCode());
                kpRatingTaskExpertScoreProgress.setCommitTime(currTime);
                kpRatingTaskExpertScoreProgress.setIsCommit(0);
                progressList.add(kpRatingTaskExpertScoreProgress);
            }
            //  发消息
            this.distributeTaskSendMsg(distributeUid, task, userEntity);
        }
        kpRatingTaskExpertDao.batchSave(expertList);
        kpRatingTaskExpertScoreProgressDao.batchSave(progressList);
    }

    private void distributeTaskSendMsg(String distributeUid, KpRatingTask task, UserEntity userEntity) {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessageGenerator(distributeUid);
        messageEntity.setMessageReceiver(userEntity.getUuid());
        //{任务管理员}提交了{任务名称}任务的预评估结果，请您审核。
        messageEntity.setMessageContent(getUsername(distributeUid) + "分发了考评任务" + task.getName() + "，请您进行打分。");
        messageService.addMessage(messageEntity);
    }

    private String getUsername(String distributeUid) {
        SUser user = userCacheService.getUser(distributeUid);
        String username = "未知用户";
        if (user != null) {
            username = user.getUserName();
        }
        return username;
    }

    /**
     * 查询关联任务面积占比
     *
     * @param provinceId 省id
     * @return
     */
    public List<KpAreaRatioOperationVo> getAreaRadioByProvinceId(String provinceId, String krtId) {
        KpRatingTaskArea kpRatingTaskAreaParam = new KpRatingTaskArea();
        kpRatingTaskAreaParam.setProvinceId(provinceId);
        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtIdAndProvinceId(krtId, provinceId);
        List<KpAreaRatioOperationVo> vos = new ArrayList<>();
        for (KpRatingTaskArea area : areaList) {
            KpAreaRatioOperationVo vo = new KpAreaRatioOperationVo();
            vo.setProvinceId(area.getProvinceId());
            vo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
            vo.setRatioId(area.getId());
            vo.setYpgTaskName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(area.getKrtytId()));
            vo.setArea(area.getArea());
            NumberFormat nf = NumberFormat.getPercentInstance();
            nf.setMaximumFractionDigits(1);//这个1的保留小数点后几位
            vo.setAreaRatio(nf.format(area.getAreaRatio()));
            vos.add(vo);
        }
        return vos;
    }

    public List<KpAreaRatioOperationVo> getAreaRadio(String krtId) {
        List<KpAreaRatioOperationVo> vos = new ArrayList<>();
        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtId(krtId);
        for (KpRatingTaskArea area : areaList) {
            KpAreaRatioOperationVo vo = new KpAreaRatioOperationVo();
            vo.setProvinceId(area.getProvinceId());
            vo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
            vo.setRatioId(area.getId());
            vo.setYpgTaskName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(area.getKrtytId()));
            vo.setArea(area.getArea());
            NumberFormat nf = NumberFormat.getPercentInstance();
            nf.setMaximumFractionDigits(1);//这个1的保留小数点后几位
            vo.setAreaRatio(nf.format(area.getAreaRatio()));
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 停止评分
     *
     * @param krtId 考评任务id
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopTask(String krtId) {
        // 修改考评任务状态
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        // 分项得分入库
        List<KpRatingTaskArea> kpRatingTaskAreaList = kpRatingTaskAreaRepository.selectByKrtId(krtId);
        if (kpRatingTaskAreaList != null) {
            for (KpRatingTaskArea kpRatingTaskArea : kpRatingTaskAreaList) {
                List<KpExamScoringDbIndex2> kpExamScoringDbIndex2List = kpExamScoringDbIndex2Repository.getByKesdId(kpRatingTask.getKesdId());
                for (KpExamScoringDbIndex2 index2 : kpExamScoringDbIndex2List) {
                    KpRatingTaskItemScore kpRatingTaskItemScore = kpRatingTaskItemScoreRepository.selectByProvinceIdAndKrtIdAndKesdi2Id(kpRatingTaskArea.getProvinceId(), krtId, index2.getId());
                    BigDecimal systemScore = kpRatingTaskIndex3ScoreRepository.getSystemScoreByKpesdi2IdAndKrtaId(index2.getId(), kpRatingTaskArea.getId());
//                    BigDecimal expertScore = kpRatingTaskIndex3ScoreRepository.getExpertScoreByKpesdi2IdAndKrtaId(index2.getId(), kpRatingTaskArea.getId());
                    // TODO 提交状态分数
                    BigDecimal expertScore = BigDecimal.ZERO;
                    // TODO 查询提交状态的分数
                    List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(kpRatingTaskArea.getKrtytId());
                    for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
                        KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());
                        // List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByExpertIdAndKrtytIdAndKpesdi2IdAndKrtaId(taskExpert.getExpertId(), kpRatingTaskExpertScoreProgress.getKrtytId(), index2.getId(), kpRatingTaskArea.getId());
                         List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getKrtytIdAndKpesdi2IdAndKrtaId(kpRatingTaskExpertScoreProgress.getKrtytId(), index2.getId(), kpRatingTaskArea.getId());
                       //last最终
                        if (index3ExpertList != null) {
                            expertScore = BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum());
                        }
                        //根据name与age进行去重
                        int size = index3ExpertList.stream().collect(
                                Collectors.collectingAndThen(Collectors.toCollection(
                                        () -> new TreeSet<>(Comparator.comparing(p -> p.getExpertId()))), ArrayList::new)
                        ).size();
                        if (size==0){
                            size=1;
                        }
                        expertScore=expertScore.divide(BigDecimal.valueOf(size));
                    }
//                    List<KpRatingTaskIndex3ScoreExpert> expertScoreList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKpesdi2IdAndKrtaId(index2.getId(), kpRatingTaskArea.getId(), kpRatingTaskArea.getKrtytId());
//                    if (expertScoreList != null) {
//                        expertScore = BigDecimal.valueOf(expertScoreList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum());
//                    }
                    if (systemScore == null) {
                        systemScore = BigDecimal.ZERO;
                    }
//                    if (expertScore == null) {
//                        expertScore = BigDecimal.ZERO;
//                    }

                    BigDecimal totalScore = (systemScore.add(expertScore)).multiply(kpRatingTaskArea.getAreaRatio());
                    // 判断是否已经有当前省的分项得分则修改，否则新增
                    if (kpRatingTaskItemScore == null) {
                        kpRatingTaskItemScore = new KpRatingTaskItemScore();
                        kpRatingTaskItemScore.setId(IdUtil.simpleUUID());
                        kpRatingTaskItemScore.setKesdi2Id(index2.getId());
                        kpRatingTaskItemScore.setDefaultScore(totalScore);
                        kpRatingTaskItemScore.setLastScore(totalScore);
                        kpRatingTaskItemScore.setProvinceId(kpRatingTaskArea.getProvinceId());
                        kpRatingTaskItemScore.setKrtId(krtId);
                        kpRatingTaskItemScoreRepository.insert(kpRatingTaskItemScore);
                    } else {
                        kpRatingTaskItemScore.setDefaultScore(totalScore.add(kpRatingTaskItemScore.getDefaultScore()));
                        kpRatingTaskItemScore.setLastScore(totalScore.add(kpRatingTaskItemScore.getLastScore()));
                        kpRatingTaskItemScoreRepository.updateById(kpRatingTaskItemScore);
                    }
                }
            }
        }
        // 修改专家评分状态
        List<KpRatingTaskYpgTask> glTaskList = kpRatingTaskYpgTaskRepository.getByKryId(krtId);
        for (KpRatingTaskYpgTask kpRatingTaskYpgTask : glTaskList) {
            KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress = new KpRatingTaskExpertScoreProgress();
            kpRatingTaskExpertScoreProgress.setCommitTime(new Date());
            kpRatingTaskExpertScoreProgress.setKrtytId(kpRatingTaskYpgTask.getId());
            kpRatingTaskExpertScoreProgress.setStatus(KpExpertRatingStatus.STOP.getCode());
            kpRatingTaskExpertScoreProgressDao.updateByKrtytId(kpRatingTaskExpertScoreProgress);
        }
        KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, 3);
        if (kpRatingTaskProgress == null) {
            kpRatingTaskProgress = new KpRatingTaskProgress();
            kpRatingTaskProgress.setId(IdUtil.simpleUUID());
            kpRatingTaskProgress.setStatus(3);
            kpRatingTaskProgress.setStatusTime(new Date());
            kpRatingTaskProgress.setKrtId(krtId);
            kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
        }
    }

    /**
     * 查看排名预览
     *
     * @param krtId     考评任务id
     * @param sortField
     * @return
     */
    public KpTaskPreviewRankingVo previewRanking(String krtId, String sortField) {
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        // 查询省份
        List<String> provinceIdList = kpRatingTaskItemScoreRepository.selectProvinceIdByKrtId(krtId);
        // 查不到省份返回空
        if (provinceIdList == null) {
            return null;
        }
        List<KpTaskPreviewRankingProvinceVo> dataList = new ArrayList<>();
        for (String provinceId : provinceIdList) {
            // 查询分项得分
            List<KpRatingTaskItemScore> kpRatingTaskIndex2ScoreList = kpRatingTaskItemScoreRepository.selectByProvinceIdAndKrtId(provinceId, krtId);
            KpTaskPreviewRankingProvinceVo kpTaskPreviewRankingProvinceVo = KpTaskPreviewRankingProvinceVo.builder().provinceName(sysAreaCacheService.getAreaNameByAreaId(provinceId)).score(BigDecimal.valueOf(kpRatingTaskIndex2ScoreList.stream().mapToDouble(o -> o.getLastScore().doubleValue()).sum())).index2ScoreList(kpRatingTaskIndex2ScoreList).build();
            dataList.add(kpTaskPreviewRankingProvinceVo);
        }
        // 列表排序
        if (!sortField.equals("score")) {
            dataList.sort((o1, o2) -> {
                BigDecimal a = BigDecimal.ZERO;
                BigDecimal b = BigDecimal.ZERO;
                for (KpRatingTaskItemScore kpRatingTaskIndex2Score : o1.getIndex2ScoreList()) {
                    if (kpRatingTaskIndex2Score.getId().equals(sortField)) {
                        a = kpRatingTaskIndex2Score.getDefaultScore();
                    }
                }
                for (KpRatingTaskItemScore kpRatingTaskIndex2Score : o2.getIndex2ScoreList()) {
                    if (kpRatingTaskIndex2Score.getId().equals(sortField)) {
                        b = kpRatingTaskIndex2Score.getDefaultScore();
                    }
                }
                return b.compareTo(a);
            });
        }
//         查询标题
        List<KpExamScoringDbIndex2> titleList = kpExamScoringDbIndex2Repository.getByKesdId(kpRatingTask.getKesdId());
        KpTaskPreviewRankingVo kpTaskPreviewRankingVo = new KpTaskPreviewRankingVo();
        kpTaskPreviewRankingVo.setDataList(dataList);
        kpTaskPreviewRankingVo.setTitleList(titleList);
        kpTaskPreviewRankingVo.setKpTaskName(kpRatingTask.getName());
        return kpTaskPreviewRankingVo;
    }

    /**
     * 修改排名
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRanking(KpRatingTaskUpdateRankingDto kpRatingTaskUpdateRankingDto) {
        // 修改考评库名称
        KpRatingTask kpRatingTask = new KpRatingTask();
        kpRatingTask.setId(kpRatingTaskUpdateRankingDto.getKrtId());
        kpRatingTask.setName(kpRatingTaskUpdateRankingDto.getKpTaskName());
        kpRatingTaskRepository.updateById(kpRatingTask);
        // 修改分项得分
        for (KpTaskPreviewRankingProvinceDto kpTaskPreviewRankingProvinceDto : kpRatingTaskUpdateRankingDto.getDataList()) {
            KpRatingTaskItemScore kpRatingTaskItemScore = new KpRatingTaskItemScore();
            kpRatingTaskItemScore.setKesdi2Id(kpTaskPreviewRankingProvinceDto.getKesdi2Id());
            kpRatingTaskItemScore.setProvinceId(kpTaskPreviewRankingProvinceDto.getProvinceId());
            kpRatingTaskItemScore.setKrtId(kpRatingTaskUpdateRankingDto.getKrtId());
            kpRatingTaskItemScore.setLastScore(kpTaskPreviewRankingProvinceDto.getScore());
            kpRatingTaskItemScoreRepository.updateByProvinceIdAndKrtIdAndKesdi2Id(kpRatingTaskItemScore);
        }
    }

    /**
     * 发布排名
     *
     * @param krtId 考评任务id
     */
    public void publishRanking(String krtId) {
        KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, 4);
        if (kpRatingTaskProgress == null) {
            kpRatingTaskProgress = new KpRatingTaskProgress();
            kpRatingTaskProgress.setId(IdUtil.simpleUUID());
            kpRatingTaskProgress.setStatus(4);
            kpRatingTaskProgress.setStatusTime(new Date());
            kpRatingTaskProgress.setKrtId(krtId);
            kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
        }
    }

    /**
     * 面积占比计算
     *
     * @param krtId
     */
    public List<KpAreaRatioOperationVo> areaProportionOperation(String krtId) {
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        List<KpAreaRatioOperationVo> volist = new ArrayList<>();
        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.selectByKrtId(krtId);
        Map<String, List<KpRatingTaskArea>> map = new HashMap<>();
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
            if (map.get(kpRatingTaskArea.getProvinceId()) == null) {
                List<KpRatingTaskArea> list = new ArrayList<>();
                list.add(kpRatingTaskArea);
                map.put(kpRatingTaskArea.getProvinceId(), list);
            } else {
                map.get(kpRatingTaskArea.getProvinceId()).add(kpRatingTaskArea);
            }
        }
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
           // int size = map.get(kpRatingTaskArea.getProvinceId()).size();
            // kpRatingTaskArea.setAreaRatio(BigDecimal.valueOf(1.0 / size));
            List<KpRatingTaskArea> kpRatingTaskAreas = map.get(kpRatingTaskArea.getProvinceId());
            kpRatingTaskArea.setAreaRatio(kpRatingTaskArea.getArea().divide(kpRatingTaskAreas.stream().map(KpRatingTaskArea::getArea).reduce(BigDecimal.ZERO,BigDecimal::add),4,RoundingMode.HALF_UP));
            kpRatingTaskAreaRepository.updateById(kpRatingTaskArea);
            if (kpRatingTaskAreas.size()>1){
                KpAreaRatioOperationVo vo = new KpAreaRatioOperationVo();
                vo.setProvinceId(kpRatingTaskArea.getProvinceId());
                vo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(kpRatingTaskArea.getProvinceId()));
                vo.setRatioId(kpRatingTaskArea.getId());
                vo.setYpgTaskName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(kpRatingTaskArea.getKrtytId()));
                vo.setArea(kpRatingTaskArea.getArea());
                NumberFormat nf = NumberFormat.getPercentInstance();
                nf.setMaximumFractionDigits(1);//这个1的保留小数点后几位
                vo.setAreaRatio(nf.format(kpRatingTaskArea.getAreaRatio()));
                volist.add(vo);
            }
        }
        kpRatingTask.setIsRunAreaRatio(1);
        kpRatingTaskRepository.updateById(kpRatingTask);
        if (PlatformObjectUtils.isNotEmpty(volist)){
            volist = volist.stream().sorted(Comparator.comparing(KpAreaRatioOperationVo::getProvinceName)).collect(Collectors.toList());
        }
        return volist;
    }

    /**
     * 计算系统得分
     *
     * @param krtId
     */
    public void systemScoreOps(String krtId) {

        kpRatingTaskService.areaProportionOperation(krtId);

        BizThreadPoolManage.exeBizThreadPoolExecutor.execute(() -> {
            this.systemScoreHandle(krtId);
        });
    }

    public void systemScoreByProvinceIdTaskOps(String krtId, String provinceId) {
        BizThreadPoolManage.exeBizThreadPoolExecutor.execute(() -> {
            this.systemScoreHandle(krtId, provinceId);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void systemScoreHandle(String krtId, String provinceId) {
        List<String> opsProgessList = new ArrayList<>();
        String cacheKey = krtId + ":" + provinceId;
        HashOperations<String, String, List<String>> ops = redisTemplate.opsForHash();
        try {
            log.debug("开始计算");
            opsProgessList.add("开始计算");
            ops.put(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, cacheKey, opsProgessList);
            KpRatingTask task = kpRatingTaskRepository.getById(krtId);
            Map<String, String> provinceMap = getProvinceMap();
            List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtIdAndProvinceId(krtId, provinceId);
            for (KpRatingTaskArea area : areaList) {
                KpRatingTaskYpgTask kpRatingTaskYpgTask = kpRatingTaskYpgTaskRepository.getById(area.getKrtytId());
                try {
                    // 查询所有3级系统指标
                    List<KpExamScoringDbIndex3WithDataVo> index3List = kpExamScoringDbIndex3Repository.getByKesdId(task.getKesdId());
                    for (KpExamScoringDbIndex3WithDataVo index3 : index3List) {
                        BigDecimal score = this.getSystemScore(provinceMap, kpRatingTaskYpgTask, index3, area.getProvinceId());
                        KpRatingTaskIndex3Score index3Score = kpRatingTaskIndex3ScoreRepository.getByKrtytIdAndkesdi3Id(kpRatingTaskYpgTask.getId(), index3.getId());
                        if (index3Score == null) {
                            KpRatingTaskIndex3Score kpRatingTaskIndex3Score = new KpRatingTaskIndex3Score();
                            kpRatingTaskIndex3Score.setId(IdUtil.simpleUUID());
                            kpRatingTaskIndex3Score.setKesdi3Id(index3.getId());
                            kpRatingTaskIndex3Score.setSystemScore(score);
                            kpRatingTaskIndex3Score.setKrtaId(area.getId());
                            kpRatingTaskIndex3ScoreRepository.insert(kpRatingTaskIndex3Score);
                        } else {
                            index3Score.setSystemScore(score);
                            kpRatingTaskIndex3ScoreRepository.updateById(index3Score);
                        }
                    }
                    opsProgessList.add(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "\t" + preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName() + "预评估任务计算完成");
                    ops.put(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, cacheKey, opsProgessList);
                    log.debug("{}\t{}预评估任务计算完成", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName());
                } catch (Exception e) {
                    opsProgessList.add(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "\t" + preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName() + "预评估任务计算失败");
                    ops.put(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, cacheKey, opsProgessList);
                    log.warn("{}\t{}预评估任务计算失败", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName());
                    log.error(e.getMessage(), e);
                }
            }
            KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, 1);
            if (kpRatingTaskProgress == null) {
                kpRatingTaskProgress = new KpRatingTaskProgress();
                kpRatingTaskProgress.setId(IdUtil.simpleUUID());
                kpRatingTaskProgress.setStatus(1);
                kpRatingTaskProgress.setStatusTime(new Date());
                kpRatingTaskProgress.setKrtId(krtId);
                kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
            }
            opsProgessList.add("计算完成");
            ops.put(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, cacheKey, opsProgessList);
            log.debug("计算完成！");
        } catch (Exception e) {
            opsProgessList.add("计算失败");
            ops.put(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, cacheKey, opsProgessList);
            log.debug("计算失败！");
            log.error(e.getMessage(), e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void systemScoreHandle(String krtId) {
        List<String> opsProgessList = new ArrayList<>();
        HashOperations<String, String, List<String>> ops = redisTemplate.opsForHash();
        try {
            log.debug("开始计算");
            opsProgessList.add("开始计算");
            ops.put(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId, opsProgessList);
            KpRatingTask task = kpRatingTaskRepository.getById(krtId);
            Map<String, String> provinceMap = getProvinceMap();
            List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtId(krtId);
            for (KpRatingTaskArea area : areaList) {
                // 查询所有3级系统指标
                KpRatingTaskYpgTask kpRatingTaskYpgTask = kpRatingTaskYpgTaskRepository.getById(area.getKrtytId());
                try {
                    List<KpExamScoringDbIndex3WithDataVo> index3List = kpExamScoringDbIndex3Repository.getByKesdId(task.getKesdId());
                    for (KpExamScoringDbIndex3WithDataVo index3 : index3List) {
                        BigDecimal score = this.getSystemScore(provinceMap, kpRatingTaskYpgTask, index3, area.getProvinceId());
                        KpRatingTaskIndex3Score index3Score = kpRatingTaskIndex3ScoreRepository.getByKrtytIdAndkesdi3Id(kpRatingTaskYpgTask.getId(), index3.getId());
                        if (index3Score == null) {
                            KpRatingTaskIndex3Score kpRatingTaskIndex3Score = new KpRatingTaskIndex3Score();
                            kpRatingTaskIndex3Score.setId(IdUtil.simpleUUID());
                            kpRatingTaskIndex3Score.setKesdi3Id(index3.getId());
                            kpRatingTaskIndex3Score.setSystemScore(score);
                            kpRatingTaskIndex3Score.setKrtaId(area.getId());
                            kpRatingTaskIndex3ScoreRepository.insert(kpRatingTaskIndex3Score);
                        } else {
                            index3Score.setSystemScore(score);
                            kpRatingTaskIndex3ScoreRepository.updateById(index3Score);
                        }
                    }
                    opsProgessList.add(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "\t" + preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName() + "预评估任务计算完成");
                    ops.put(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId, opsProgessList);
                    log.debug("{}\t{}预评估任务计算完成", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName());
                } catch (Exception e) {
                    opsProgessList.add(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "\t" + preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName() + "预评估任务计算失败");
                    ops.put(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId, opsProgessList);
                    log.warn("{}\t{}预评估任务计算失败", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), preAssessTaskService.getById(kpRatingTaskYpgTask.getYpgTaskId()).getTaskName());
                    log.error(e.getMessage(), e);
                }
            }
            opsProgessList.add("计算完成");
            ops.put(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId, opsProgessList);
            log.debug("计算完成！");
            KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, 1);
            if (kpRatingTaskProgress == null) {
                kpRatingTaskProgress = new KpRatingTaskProgress();
                kpRatingTaskProgress.setId(IdUtil.simpleUUID());
                kpRatingTaskProgress.setStatus(1);
                kpRatingTaskProgress.setStatusTime(new Date());
                kpRatingTaskProgress.setKrtId(krtId);
                kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
            }
        } catch (Exception e) {
            opsProgessList.add("计算完成");
            ops.put(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId, opsProgessList);
            log.debug("计算完成！");
            log.error(e.getMessage(), e);
        }
    }

    private BigDecimal getSystemScore(Map<String, String> provinceMap, KpRatingTaskYpgTask kpRatingTaskYpgTask, KpExamScoringDbIndex3WithDataVo index3, String currProvinceId) {
        BigDecimal score = BigDecimal.ZERO;
        switch (index3.getCode()) {
            case "1":
                score = runSystemScoreService.getSystemScoreNum1(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "2":
                score = runSystemScoreService.getSystemScoreNum2(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "3":
                score = runSystemScoreService.getSystemScoreNum3(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "4":
                score = runSystemScoreService.getSystemScoreNum4(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "5":
                score = runSystemScoreService.getSystemScoreNum5(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "6":
                score = runSystemScoreService.getSystemScoreNum6(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "7":
                score = runSystemScoreService.getSystemScoreNum7(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "8":
                score = runSystemScoreService.getSystemScoreNum8(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "9":
                score = runSystemScoreService.getSystemScoreNum9(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "10":
                score = runSystemScoreService.getSystemScoreNum10(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "11":
                score = runSystemScoreService.getSystemScoreNum11(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "12":
                score = runSystemScoreService.getSystemScoreNum12(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "13":
                score = runSystemScoreService.getSystemScoreNum13(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "14":
                score = runSystemScoreService.getSystemScoreNum14(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "15":
                score = runSystemScoreService.getSystemScoreNum15(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "16":
                score = runSystemScoreService.getSystemScoreNum16(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "17":
                score = runSystemScoreService.getSystemScoreNum17(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "18":
                score = runSystemScoreService.getSystemScoreNum18(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "19":
                score = runSystemScoreService.getSystemScoreNum19(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "20":
                score = runSystemScoreService.getSystemScoreNum20(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "21":
                score = runSystemScoreService.getSystemScoreNum21(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "22":
                score = runSystemScoreService.getSystemScoreNum22(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "23":
                score = runSystemScoreService.getSystemScoreNum23(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "24":
                score = runSystemScoreService.getSystemScoreNum24(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "25":
                score = runSystemScoreService.getSystemScoreNum25(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), provinceMap, currProvinceId);
                break;
            case "26":
                score = runSystemScoreService.getSystemScoreNum26(currProvinceId, index3.getScore(), index3.getId(), currProvinceId);
                break;
            case "27":
                score = runSystemScoreService.getSystemScoreNum27(currProvinceId, index3.getScore());
                break;
            case "28":
                score = runSystemScoreService.getSystemScoreNum28(currProvinceId, index3.getScore());
                break;
            case "29":
                score = runSystemScoreService.getSystemScoreNum29(currProvinceId, index3.getScore());
                break;
            case "30":
                score = runSystemScoreService.getSystemScoreNum30(currProvinceId, index3.getScore());
                break;
            case "31":
                score = runSystemScoreService.getSystemScoreNum31(currProvinceId, index3.getScore());
                break;
            case "32":
                score = runSystemScoreService.getSystemScoreNum32(currProvinceId, index3.getScore());
                break;
            case "33":
                score = runSystemScoreService.getSystemScoreNum33(currProvinceId, index3.getScore());
                break;
            case "34":
                score = runSystemScoreService.getSystemScoreNum34(kpRatingTaskYpgTask.getYpgTaskId(), index3.getScore(), currProvinceId);
                break;
            case "35":
                score = runSystemScoreService.getSystemScoreNum35(kpRatingTaskYpgTask.getYpgTaskId(), kpRatingTaskYpgTask.getXcdcTaskId(), currProvinceId, index3.getScore(), provinceMap);
                break;
            case "36":
                score = runSystemScoreService.getSystemScoreNum36(kpRatingTaskYpgTask.getXcdcTaskId(), currProvinceId, index3.getScore());
                break;
            case "37":
                score = runSystemScoreService.getSystemScoreNum37(currProvinceId, kpRatingTaskYpgTask.getXcdcTaskId(), index3.getScore());
                break;
            case "38":
                score = runSystemScoreService.getSystemScoreNum38(kpRatingTaskYpgTask.getYpgTaskId(), currProvinceId, provinceMap, index3.getScore());
                break;
            case "39":
                score = runSystemScoreService.getSystemScoreNum39(kpRatingTaskYpgTask.getYpgTaskId(), kpRatingTaskYpgTask.getXcdcTaskId(), index3.getScore());
                break;
            case "40":
                score = runSystemScoreService.getSystemScoreNum40(kpRatingTaskYpgTask.getYpgTaskId(), kpRatingTaskYpgTask.getXcdcTaskId(), index3.getScore());
                break;
            case "41":
                score = runSystemScoreService.getSystemScoreNum41(kpRatingTaskYpgTask.getYpgTaskId(), kpRatingTaskYpgTask.getXcdcTaskId(), index3.getScore());
                break;
        }
        return score;
    }

    public void cleanLatestUnsaveTaskToCache(String currUid) {
        HashOperations<String, String, NewKpTaskDto> hashOps = redisTemplate.opsForHash();
        hashOps.delete(CURR_USER_LATEST_CREATING_KP_TASK, currUid);
    }

    private Map<String, String> getProvinceMap() {
        String provinceListStr = sysAreaService.jsonSAreaTree("1");
        JSONArray dataJSONArr = JSONObject.parseArray(provinceListStr);
        Map<String, String> areaMap = new HashMap<>();
        for (Object o : dataJSONArr) {
            areaMap.put(JSONObject.parseObject(JSONObject.toJSONString(o)).getString("name"), JSONObject.parseObject(JSONObject.toJSONString(o)).getString("id"));
        }
        return areaMap;
    }

    public List<String> getSystemScoreOpsing(String krtId) {
        HashOperations<String, String, List<String>> ops = redisTemplate.opsForHash();
        return ops.get(KP_TASK_SYSTEM_SCORE_SCHEDULE, krtId);
    }

    public List<String> getAreaSystemScoreOpsing(String krtId, String provinceId) {
        HashOperations<String, String, List<String>> ops = redisTemplate.opsForHash();
        return ops.get(KP_PROVINCE_SYSTEM_SCORE_SCHEDULE, krtId + ":" + provinceId);
    }

    /**
     * 查询专家列表
     *
     * @param krtId
     * @return
     */
    public String getExpertByGroupId(String krtId) {
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        if (kpRatingTask == null) {
            return null;
        }
        GroupEntity groupEntity = groupService.getById(kpRatingTask.getExpertGroupId());
        if (groupEntity == null) {
            return null;
        }
        return groupEntity.getGroupExpert();
    }

    /**
     * 考评库是否有任务占用
     *
     * @param kpkId
     * @return
     */
    public int kpkIsUse(String kpkId) {
        Integer total = kpRatingTaskRepository.countByKesdId(kpkId);
        return total == 0 ? 0 : 1;
    }

    public List<KpRatingTask> getTaskRankList(KpRatingTask kpRatingTask) {
        return kpRatingTaskRepository.selectByStatus(kpRatingTask, 4);
    }

    public void deleteCache(String key) {
        redisTemplate.delete(key);
    }

    public List<ExpertScoreProgressVO> expertScoreProgress(String krtytId) {
        List<ExpertScoreProgressVO> list = kpRatingTaskRepository.expertScoreProgress(krtytId);
        return list.stream()
                .peek(o -> {
                    o.setName(CreateGson.createGson().fromJson(sUserService.getSUser(o.getExpertId()), SUser.class).getUserName());
                if (o.getStatus()==0 || o.getStatus()==1 || o.getStatus()==null){
                o.setStatus(0);
                }
                else {
                    o.setStatus(1);
                }
                }).collect(Collectors.toList());


    }

    public List<KpIndexScoreDetailsVo> getGlTaskScoreDetailsFinal(String provinceId, String krtId) {
        // 查询某省份下的的所有关联任务
        List<KpRatingTaskYpgTask> taskList = kpRatingTaskYpgTaskRepository.getByProvinceId(provinceId, krtId);
        if (taskList == null) {
            log.warn("当前区域下找不到预评估任务");
            return null;
        }
        List<KpIndexScoreDetailsVo> resList = new ArrayList<>();
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        if (kpRatingTask == null) {
            throw new RuntimeException("考评任务id错误");
        }
        // 查询指标库下的指标
        List<KpExamScoringDbIndex1Vo> kpExamScoringDbIndex1VoList = kpExamScoringDbService.getIndex(kpRatingTask.getKesdId());
        for (KpRatingTaskYpgTask task : taskList) {
            List<KpIndexScoreDetailsVo.AreaScore> totalSystemScore = new ArrayList<>();
            BigDecimal totalExpertScore = BigDecimal.ZERO;
            List<KpIndexScoreVo> indexList = new ArrayList<>();
            // 指标库下没有指标，构建任务名称和空的指标列表vo
            if (kpExamScoringDbIndex1VoList == null) {
                resList.add(buildEmptyIndexScoreDetailsVo(task));
                continue;
            }
            // 根据指标构建vo
            for (KpExamScoringDbIndex1Vo index1 : kpExamScoringDbIndex1VoList) {
                if (index1.getChildren() == null) {
                    indexList.add(buildEmptyIndexScoreVoByIndex1(index1));
                    continue;
                }
                BigDecimal index1Score = kpExamScoringDbIndex3Repository.sumScoreByKesdi1Id(index1.getId());
                for (KpExamScoringDbIndex2Vo index2 : index1.getChildren()) {
                    if (index2.getChildren() == null) {
                        KpIndexScoreVo kpIndexScoreVo = buildEmptyIndexScoreVoByIndex2(index1, index2);
                        indexList.add(kpIndexScoreVo);
                        continue;
                    }
                    double index2Score = index2.getChildren().stream().mapToDouble(o -> o.getScore().doubleValue()).sum();
                    for (KpExamScoringDbIndex3Vo index3 : index2.getChildren()) {
                        KpIndexScoreVo kpIndexScoreVo = new KpIndexScoreVo();
                        List<KpIndexScoreVo.SystemScore> systemScoreList = kpIndexScoreVo.getSystemScoreList();
                        KpIndex3Data kpIndex3Data = index3.getKpIndex3Data();
                        // get expert score
//                        BigDecimal expertScore = kpRatingTaskIndex3ScoreExpertRepository.sumScoreByKesdi3IdAndKrtytId(index3.getId(), task.getId());
                        BigDecimal expertScore = BigDecimal.ZERO;
                        // TODO 查询提交状态的分数
                        List<KpRatingTaskExpertScoreProgress> progressList = kpRatingTaskExpertScoreProgressDao.getCommitByKrtytId(task.getId());
                        for (KpRatingTaskExpertScoreProgress kpRatingTaskExpertScoreProgress : progressList) {
                           // KpRatingTaskExpert taskExpert = kpRatingTaskExpertDao.getById(kpRatingTaskExpertScoreProgress.getKrteId());
                            //专家评分采用平均值
                            List<KpRatingTaskIndex3ScoreExpert> index3ExpertList = kpRatingTaskIndex3ScoreExpertRepository.getByKrtytIdAndKesdi3Id(kpRatingTaskExpertScoreProgress.getKrtytId(), index3.getId());
                         //   Integer num=kpRatingTaskIndex3ScoreExpertRepository.getExportNumByKrtId(krtId);

                            if (PlatformObjectUtils.isNotEmpty(index3ExpertList)) {
                                int i=0;
                                for (KpRatingTaskIndex3ScoreExpert kpRatingTaskIndex3ScoreExpert : index3ExpertList) {
                                    if (PlatformObjectUtils.isNotEmpty(kpRatingTaskIndex3ScoreExpert.getScore())){
                                        i++;
                                    }
                                }
                                expertScore = BigDecimal.valueOf(index3ExpertList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum()).divide(new BigDecimal(i),1);
                            }
                        }
//                        List<KpRatingTaskIndex3ScoreExpert> expertScoreList = kpRatingTaskIndex3ScoreExpertRepository.getCommitedDataByKesdi3IdAndKrtytyId(index3.getId(), task.getId());
//                        if (expertScoreList != null) {
//                            expertScore = BigDecimal.valueOf(expertScoreList.stream().mapToDouble(e -> e.getScore().doubleValue()).sum());
//                        }
                        // get system score list
                        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.getByKrtytId(task.getId());
                        for (KpRatingTaskArea area : areaList) {
                            KpIndexScoreVo.SystemScore systemScoreVo = new KpIndexScoreVo.SystemScore();
                            systemScoreVo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
                            BigDecimal score = kpRatingTaskIndex3ScoreRepository.sumScoreByKesdi3IdAndKrtaId(index3.getId(), area.getId());
                            if (score == null) {
                                score = BigDecimal.ZERO;
                            }
                            systemScoreVo.setSystemScore(score);
                            systemScoreList.add(systemScoreVo);
                            boolean flag = false;
                            for (KpIndexScoreDetailsVo.AreaScore areaScore : totalSystemScore) {
                                if (areaScore.getProvinceName().equals(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()))) {
                                    areaScore.setTotalSystemScore(areaScore.getTotalSystemScore().add(score));
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) {
                                KpIndexScoreDetailsVo.AreaScore areaScore = new KpIndexScoreDetailsVo.AreaScore();
                                areaScore.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(area.getProvinceId()));
                                areaScore.setTotalSystemScore(score);
                                totalSystemScore.add(areaScore);
                            }
                        }
                        // 计算系统得分和专家得分的总分数
                        totalExpertScore = totalExpertScore.add(expertScore == null ? BigDecimal.ZERO : expertScore);
                        kpIndexScoreVo.setIndex1Id(index1.getId());
                        kpIndexScoreVo.setIndex1Name(index1.getName());
                        kpIndexScoreVo.setIndex1Score(index1Score);
                        kpIndexScoreVo.setIndex2Id(index2.getId());
                        kpIndexScoreVo.setIndex2Name(index2.getName());
                        kpIndexScoreVo.setIndex2Score(BigDecimal.valueOf(index2Score));
                        kpIndexScoreVo.setIndex3Id(index3.getId());
                        kpIndexScoreVo.setKpIndex3Data(kpIndex3Data);
                        kpIndexScoreVo.setIndex3Score(index3.getScore());
                        kpIndexScoreVo.setIndex3Standard(index3.getIndexStandard());



                        //现在应该用平均分
                        kpIndexScoreVo.setExpertScore(expertScore == null ? BigDecimal.ZERO : expertScore);
                        indexList.add(kpIndexScoreVo);
                    }
                }
            }
            BigDecimal finalTotalExpertScore = totalExpertScore;
            totalSystemScore.forEach(o -> {
                o.setTotalScore(finalTotalExpertScore.add(o.getTotalSystemScore()));
            });
            KpIndexScoreDetailsVo kpIndexScoreDetailsVo = new KpIndexScoreDetailsVo();
            kpIndexScoreDetailsVo.setYpgId(task.getYpgTaskId());
            kpIndexScoreDetailsVo.setKrtytId(task.getId());
            kpIndexScoreDetailsVo.setYpgName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(task.getId()));
            kpIndexScoreDetailsVo.setTotalExpertScore(totalExpertScore);
            kpIndexScoreDetailsVo.setAreaScoreList(totalSystemScore);
            kpIndexScoreDetailsVo.setIndexList(indexList);
            resList.add(kpIndexScoreDetailsVo);
        }
        return resList;
    }

    public List<KpAreaRatioOperationVo> areaProportionOperationPg(String krtId) {
        KpRatingTask kpRatingTask = kpRatingTaskRepository.getById(krtId);
        List<KpAreaRatioOperationVo> volist = new ArrayList<>();
        List<KpRatingTaskArea> areaList = kpRatingTaskAreaRepository.selectByKrtId(krtId);
        Map<String, List<KpRatingTaskArea>> map = new HashMap<>();
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
            if (map.get(kpRatingTaskArea.getProvinceId()) == null) {
                List<KpRatingTaskArea> list = new ArrayList<>();
                list.add(kpRatingTaskArea);
                map.put(kpRatingTaskArea.getProvinceId(), list);
            } else {
                map.get(kpRatingTaskArea.getProvinceId()).add(kpRatingTaskArea);
            }
        }
        for (KpRatingTaskArea kpRatingTaskArea : areaList) {
            // int size = map.get(kpRatingTaskArea.getProvinceId()).size();
            // kpRatingTaskArea.setAreaRatio(BigDecimal.valueOf(1.0 / size));
            List<KpRatingTaskArea> kpRatingTaskAreas = map.get(kpRatingTaskArea.getProvinceId());
            /*kpRatingTaskArea.setAreaRatio(kpRatingTaskArea.getArea().divide(kpRatingTaskAreas.stream().map(KpRatingTaskArea::getArea).reduce(BigDecimal.ZERO,BigDecimal::add),2,RoundingMode.HALF_UP));
            kpRatingTaskAreaRepository.updateById(kpRatingTaskArea);*/
            if (kpRatingTaskAreas.size()>1){
                KpAreaRatioOperationVo vo = new KpAreaRatioOperationVo();
                vo.setProvinceId(kpRatingTaskArea.getProvinceId());
                vo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(kpRatingTaskArea.getProvinceId()));
                vo.setRatioId(kpRatingTaskArea.getId());
                vo.setYpgTaskName(kpRatingTaskYpgTaskRepository.getYpgNameByKrtytId(kpRatingTaskArea.getKrtytId()));
                vo.setArea(kpRatingTaskArea.getArea());
                NumberFormat nf = NumberFormat.getPercentInstance();
                nf.setMaximumFractionDigits(1);//这个1的保留小数点后几位
                vo.setAreaRatio(nf.format(kpRatingTaskArea.getAreaRatio()));
                volist.add(vo);
            }
        }
       /* kpRatingTask.setIsRunAreaRatio(1);
        kpRatingTaskRepository.updateById(kpRatingTask);*/
        if (PlatformObjectUtils.isNotEmpty(volist)){
            volist = volist.stream().sorted(Comparator.comparing(KpAreaRatioOperationVo::getProvinceName)).collect(Collectors.toList());
        }
        return volist;
    }
}
